export default {
  namespaced: true,
  state: () => ({
    cart: JSON.parse(uni.getStorageSync('cart')||'[]')
  }),
  mutations: {
    addToCart(state, goods) {
      // 如果是否的话返回这个值
      const findGoods = state.cart.find((item) => item.goods_id === goods.goods_id)
      if (!findGoods) {
        state.cart.push(goods)
      } else {
      // 如果有商品，则增加数量
        findGoods.goods_count++
      }
      this.commit('m_cart/saveTo')
    },
    // 实现本地储存
    saveTo(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    // 修改仓库中radio的state
    changeState(state,val){
      const findRes=state.cart.find(item=>item.goods_id===val.id)
      console.log(findRes);
      findRes.goods_state=val.state
      this.commit('m_cart/saveTo')
    },
    // 修改商品的数量
    changeCount(state,val){
      const findRes=state.cart.find(item=>item.goods_id===val.id)
      findRes.goods_count=val.count
      this.commit('m_cart/saveTo')
    },
    // 删除商品
    removeGoodsById(state,val){
      // 筛选出不是该id的
      state.cart=state.cart.filter(item=>item.goods_id!==val)
      this.commit('m_cart/saveTo')
    },
    //修改全部商品的状态
    stateAllChange(state,fullCheck){
      state.cart.forEach(item=>item.goods_state=fullCheck)
      this.commit('m_cart/saveTo')
    }
  },
  getters: {
    allCount(state) {
      return state.cart.reduce((total,item)=>total+=item.goods_count,0)
    },
    // 计算勾选商品的总数量
    checkCount(state){
      return state.cart.filter(val=>val.goods_state==true).reduce((total,item)=>total+=item.goods_count,0)
    },
    // 计算已经勾选状态的总价格
    allMoney(state){
      return state.cart.filter(item=>item.goods_state==true).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
      
    }
  }
}
